package com.bizark.rpc.common.aop;

import com.bizark.rpc.common.annotation.DataSourceKey;
import com.bizark.rpc.common.dao.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by dingjingyang on 2017/2/27.
 */
@Aspect
@Component
public class MultipleDataSourceAspectAdvice {

    @Pointcut("@annotation(com.bizark.rpc.common.annotation.DataSourceKey)")
    public void dataSourceAspect() {
    }

    @Around("dataSourceAspect()")
    public Object invoke(ProceedingJoinPoint point) throws Throwable {
        String value = "";
        String methodName = point.getSignature().getName();
        String targetName = point.getTarget().getClass().getName();
        Object[] arguments = point.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    value = method.getAnnotation(DataSourceKey.class).dataSource().getDataSourceName();
                    break;
                }
            }
        }
        if (value.length() > 0) {
            DataSourceContextHolder.setDataSourceType(value);
        }
        return point.proceed();
    }


}
